const {login} = require('../controller/user')
const {SuccessModel, ErrorModel} = require('../model/resModel')
const {set} = require('../db/redis')

const handleUserRouter = (req, res) => {
    const {method, url}= req

    const path = url.split('?')[0]

    // 登录
    if(method === 'POST' && path === '/api/user/login'){
        const {username, password} = req.body
        
        let result= login(username, password)
        return result.then(data => {
            if(data.username){
                req.session.username = data.username
                req.session.realname = data.realname
                // 同步redis
                set(req.sessionId, req.session)
                return new SuccessModel({username}, '登录成功')
            }
            return new ErrorModel(null, '登录失败')
        })
    }

    // 验证是否登录
    // if(method === 'GET' && req.path === '/api/user/login-test') {
    //     if(req.session.username) {
    //         return Promise.resolve(new SuccessModel({
    //             session: req.session
    //         }))
    //     }
    //     return Promise.resolve(new ErrorModel('登录失败'))
    // }
}
module.exports = handleUserRouter